package javaNIO1.channel;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.DatagramChannel;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * Created with Intel IDEA.
 * 时间服务器
 * @Auther: gjt
 * @Date: 2024/7/21 13:59
 */
public class TimeServer {
    private static final int PORT = 37;
    protected DatagramChannel datagramChannel;

    private static  final long DIFF_1900 = 2208988800L;

    public TimeServer(int port) throws IOException {
        this.datagramChannel = DatagramChannel.open();
        this.datagramChannel.bind(new InetSocketAddress(port));
        System.out.println("Listening on port " + port + "for time requests");
    }

    public void listen() throws IOException {
        ByteBuffer longBuffer = ByteBuffer.allocateDirect(8);
        longBuffer.order(ByteOrder.BIG_ENDIAN);

        longBuffer.putLong(0,0);

        longBuffer.position(4);

        // 复制一个从原始缓冲区位置开始 ，容量是原来缓冲区中剩余元素的个数
        ByteBuffer sliceBuffer = longBuffer.slice();

        /**
         * 注意： 可以这理解缓冲区前半部分 用于写入时间 后半部分用于接收请求的地址
         */
        while(true){
            sliceBuffer.clear();
            SocketAddress receive = this.datagramChannel.receive(sliceBuffer);

            if(Objects.isNull(receive)){
                continue;
            }
            System.out.println("This request from " + receive);
            // 用完后半部分就清空了
            sliceBuffer.clear();

            // 时间写入到 longBuffer 的前一半
            longBuffer.putLong(0,(System.currentTimeMillis()/1000) + DIFF_1900);

            // 问题
//            this.datagramChannel.send(sliceBuffer, receive);
            this.datagramChannel.send(longBuffer, receive);
        }
    }

    public static void main(String[] args) {
        int port = PORT;
        try {
            TimeServer timeServer = new TimeServer(port);
            timeServer.listen();
        } catch (IOException e) {
          e.printStackTrace();
        }
    }

}
